package com.hnichr.ping.sms.channel.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.hnichr.ping.common.DictEnum;
import com.hnichr.ping.common.vo.MobileResultVo;
import com.hnichr.ping.common.vo.SendResultVo;
import com.hnichr.ping.common.vo.SmsSendVo;
import com.hnichr.ping.sms.channel.SmsChannelProvider;
import com.hnichr.ping.sms.entity.SmsChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AliyunSmsChannelProvider implements SmsChannelProvider {
    private static final Logger logger = LoggerFactory.getLogger(AliyunSmsChannelProvider.class);

    private static final String PROVIDER_CODE = "aliyun";

    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    private ConcurrentHashMap<String,Client> clientMap = new ConcurrentHashMap<>();

    @Override
    public String getProviderCode() {
        return PROVIDER_CODE ;
    }

    @Override
    public SendResultVo paramVerify(SmsSendVo smsSendVo){
        if(StringUtils.isBlank(smsSendVo.getTemplateCode())){
            return SendResultVo.failed("templateCode不能为空");
        }
        return SendResultVo.success();
    }

    @Override
    public SendResultVo send(SmsChannel channel, SmsSendVo smsSendVo) {

        Client client = clientMap.get(channel.getChannelCode());
        if(client == null){
            synchronized (this){
                try{
                    client = clientMap.get(channel.getChannelCode());
                    if(client == null){
                        Config config = new Config()
                                .setAccessKeyId(channel.getPrincipal())
                                .setAccessKeySecret(channel.getIdentity());
                        // 配置 Endpoint
                        config.endpoint = ENDPOINT;
                        client = new Client(config);
                        clientMap.put(channel.getChannelCode(),client);
                    }
                }
                catch (Exception e){
                    logger.error("初始化aliyun client失败",e);
                    return SendResultVo.failed("初始化client失败");
                }
            }
        }
        // 构造请求对象，请填入请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(smsSendVo.getMobiles())
                .setSignName(channel.getPerfix())
                .setTemplateCode(smsSendVo.getTemplateCode())
                .setTemplateParam(JSON.toJSONString(smsSendVo.getTemplateParams()));
        // 获取响应对象
        try{
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            SendResultVo sendResultVo = SendResultVo.success();
            for(String mobile:smsSendVo.getMobiles().split(",")){
                MobileResultVo vo = new MobileResultVo();
                vo.setMobile(mobile);
                vo.setResultCode(DictEnum.SEND_RESULT.OK.getCode());
                sendResultVo.getResult().add(vo);
            }
            return sendResultVo;

        }
        catch (Exception e){
            return SendResultVo.failed("发送失败");
        }
    }
}
